package com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.HddcFaultsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.HddcFaultsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.entity.HddcFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.service.HddcFaultsvypointService;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.viewobjects.HddcFaultsvypointPageVO;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.viewobjects.HddcFaultsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.viewobjects.HddcFaultsvypointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author lihelei
 * @date 2020-11-26
 */
@Service
public class HddcFaultsvypointServiceImpl implements HddcFaultsvypointService {

	@Autowired
    private HddcFaultsvypointRepository hddcFaultsvypointRepository;
    @Autowired
    private HddcFaultsvypointNativeRepository hddcFaultsvypointNativeRepository;

    @Override
    public JSONObject queryHddcFaultsvypoints(HddcFaultsvypointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcFaultsvypointPageVO> hddcFaultsvypointPage = this.hddcFaultsvypointNativeRepository.queryHddcFaultsvypoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcFaultsvypointPage);
    }


    @Override
    public HddcFaultsvypointEntity getHddcFaultsvypoint(String id) {
        return this.hddcFaultsvypointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcFaultsvypointEntity saveHddcFaultsvypoint(HddcFaultsvypointEntity hddcFaultsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcFaultsvypoint.setUuid(uuid);
        hddcFaultsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcFaultsvypoint.setCreateTime(now);
        hddcFaultsvypoint.setUpdateTime(now);
        hddcFaultsvypoint.setIsValid(PlatformConstants.Y);
        hddcFaultsvypoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcFaultsvypoint.setExtends10(PlatformConstants.Y);
        this.hddcFaultsvypointRepository.save(hddcFaultsvypoint);
        return hddcFaultsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcFaultsvypointEntity updateHddcFaultsvypoint(HddcFaultsvypointEntity hddcFaultsvypoint) {
        HddcFaultsvypointEntity entity = hddcFaultsvypointRepository.findById(hddcFaultsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcFaultsvypoint);
        hddcFaultsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcFaultsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcFaultsvypointRepository.save(hddcFaultsvypoint);
        return hddcFaultsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcFaultsvypoints(List<String> ids) {
        List<HddcFaultsvypointEntity> hddcFaultsvypointList = this.hddcFaultsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcFaultsvypointList) && hddcFaultsvypointList.size() > 0) {
            for(HddcFaultsvypointEntity hddcFaultsvypoint : hddcFaultsvypointList) {
                hddcFaultsvypoint.setIsValid("0");
                hddcFaultsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFaultsvypoint.setUpdateTime(new Date());
                this.hddcFaultsvypointRepository.save(hddcFaultsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcFaultsvypointQueryParams queryParams, HttpServletResponse response) {
        List<HddcFaultsvypointEntity> yhDisasterEntities = hddcFaultsvypointNativeRepository.exportYhDisasters(queryParams);
        List<HddcFaultsvypointVO> list=new ArrayList<>();
        for (HddcFaultsvypointEntity entity:yhDisasterEntities) {
            HddcFaultsvypointVO yhDisasterVO=new HddcFaultsvypointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"断层观测点-点","断层观测点-点",HddcFaultsvypointVO.class,"断层观测点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcFaultsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcFaultsvypointVO.class, params);
            List<HddcFaultsvypointVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcFaultsvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcFaultsvypointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcFaultsvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcFaultsvypointEntity yhDisasterEntity = new HddcFaultsvypointEntity();
            HddcFaultsvypointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcFaultsvypoint(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcFaultsvypointEntity> hddcFaultsvypointList = this.hddcFaultsvypointRepository.queryHddcFaultsvypointsByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcFaultsvypointList) && hddcFaultsvypointList.size() > 0) {
            for(HddcFaultsvypointEntity hddcFaultsvypoint : hddcFaultsvypointList) {
                hddcFaultsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFaultsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcFaultsvypoint.setIsValid("0");
                this.hddcFaultsvypointRepository.save(hddcFaultsvypoint);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskIds
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcFaultsvypointEntity> hddcFaultsvypointList = this.hddcFaultsvypointRepository.queryHddcFaultsvypointsByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcFaultsvypointList) && hddcFaultsvypointList.size() > 0) {
            for(HddcFaultsvypointEntity hddcFaultsvypoint : hddcFaultsvypointList) {
                hddcFaultsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcFaultsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcFaultsvypoint.setIsValid("0");
                this.hddcFaultsvypointRepository.save(hddcFaultsvypoint);
            }
        }

    }

}
